/**
 * @file compiler.cpp
 * @brief VimL编译器实现 - 支持调试信息生成
 * @author VimLVM Team
 * @date 2025
 */

#include "viml/compiler.h"
#include <sstream>
#include <algorithm>
#include <cctype>
#include <iostream>


namespace viml {

Compiler::Compiler() = default;

CompileResult Compiler::compile(const std::string& source, const std::string& filename) {
    CompileResult result;
    CompileContext ctx(filename);
    
    // 分割源文件为行
    std::istringstream stream(source);
    std::string line;
    while (std::getline(stream, line)) {
        ctx.source_lines.push_back(line);
    }
    
    // 创建函数
    auto function = std::make_shared<Function>();
    function->name = filename;
    function->debug_info = ctx.debug_info;
    
    // 辅助函数：分配寄存器
    auto allocate_register = [&ctx](const std::string& var_name) -> size_t {
        size_t reg = ctx.next_register++;
        ctx.variable_registers[var_name] = reg;
        return reg;
    };

    // 设置编译上下文中的函数
    ctx.function = function;
    
    // 简单的编译逻辑 - Phase 0基础实现
    size_t line_num = 0;
    for (const auto& line : ctx.source_lines) {
        line_num++;
        size_t bytecode_start = ctx.function->bytecode.size();
        std::string trimmed = line;
        trimmed.erase(0, trimmed.find_first_not_of(" \t"));
        trimmed.erase(trimmed.find_last_not_of(" \t\r\n") + 1);
        
        if (trimmed.empty() || trimmed[0] == '"') {
            continue; // 跳过空行和注释
        }
        
        // 记录当前语句的起始字节码位置
        size_t stmt_start = ctx.function->bytecode.size();
        
        // 处理各种语句
        if (trimmed.find("let ") == 0) {
            if (!compile_let_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile let statement: " + trimmed);
                return result;
            }
        } else if (trimmed.find("echo ") == 0) {
            if (!compile_echo_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile echo statement: " + trimmed);
                return result;
            }
        } else if (trimmed.rfind("if", 0) == 0) {
            // 以"if"开头的语句
            if (!compile_if_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile if statement at line " + std::to_string(line_num) + ": " + trimmed);
                return result;
            }
        } else if (trimmed.rfind("elseif", 0) == 0) {
            // 以"elseif"开头的语句
            if (!compile_elseif_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile elseif statement: " + trimmed);
                return result;
            }
        } else if (trimmed == "else") {
            if (!compile_else_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile else statement: " + trimmed);
                return result;
            }
        } else if (trimmed == "endif") {
            if (!compile_endif_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile endif statement: " + trimmed);
                return result;
            }
        } else if (trimmed.rfind("while", 0) == 0) {
            // 以"while"开头的语句
            if (!compile_while_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile while statement: " + trimmed);
                return result;
            }
        } else if (trimmed == "endwhile") {
            if (!compile_endwhile_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile endwhile statement: " + trimmed);
                return result;
            }
        } else if (trimmed.rfind("for", 0) == 0) {
            // 以"for"开头的语句
            if (!compile_for_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile for statement: " + trimmed);
                return result;
            }
        } else if (trimmed == "endfor") {
            if (!compile_endfor_statement(trimmed, ctx, line_num)) {
                result.errors.push_back("Failed to compile endfor statement: " + trimmed);
                return result;
            }
        }
        // 为当前语句添加行号映射
        if (ctx.function->bytecode.size() > stmt_start) {
            update_line_mapping(ctx, stmt_start, line_num);
        }
    }
    
    // 确保有返回指令
    if (ctx.function->bytecode.empty()) {
        size_t const_idx = add_constant(ctx, Value(0.0));
        ctx.function->bytecode.push_back(Instruction::load_const(0, const_idx));
        ctx.function->bytecode.push_back(Instruction(OpCode::RETURN_OP, 0));
    } else if (ctx.function->bytecode.back().opcode != OpCode::RETURN_OP) {
        // 添加隐式返回
        ctx.function->bytecode.push_back(Instruction(OpCode::RETURN_OP, 0));
    }
    
    // 将常量池转移到Function对象中
    function->constants = std::move(ctx.constant_pool);
    
    result.function = function;
    result.success = true;
    return result;
}

std::vector<std::string> Compiler::tokenize(const std::string& source) {
    std::vector<std::string> tokens;
    std::istringstream stream(source);
    std::string token;
    while (stream >> token) {
        tokens.push_back(token);
    }
    return tokens;
}

size_t Compiler::compile_expression(const std::string& expr, CompileContext& ctx) {
    std::string trimmed = expr;
    trimmed.erase(0, trimmed.find_first_not_of(" \t"));
    trimmed.erase(trimmed.find_last_not_of(" \t\r\n") + 1);
    
    // 处理括号
    if (!trimmed.empty() && trimmed.front() == '(' && trimmed.back() == ')') {
        trimmed = trimmed.substr(1, trimmed.length() - 2);
        trimmed.erase(0, trimmed.find_first_not_of(" \t"));
        trimmed.erase(trimmed.find_last_not_of(" \t\r\n") + 1);
    }
    
    // 处理比较表达式（优先级最低）
    // 从右到左查找比较运算符，确保正确的结合性
    // 注意：需要确保运算符不在括号内
    int paren_count = 0;
    for (int i = static_cast<int>(trimmed.length()) - 1; i >= 0; i--) {
        if (trimmed[i] == ')') {
            paren_count++;
        } else if (trimmed[i] == '(') {
            paren_count--;
        } else if (paren_count == 0 && i > 0) {
            // 检查当前位置是否是某个比较运算符的结尾
            for (const auto& cmp : compare_ops) {
                if (i >= static_cast<int>(cmp.op.length()) - 1 && 
                    trimmed.substr(i - cmp.op.length() + 1, cmp.op.length()) == cmp.op) {
                    std::string left_str = trimmed.substr(0, i - cmp.op.length() + 1);
                    std::string right_str = trimmed.substr(i + 1);
                    
                    size_t left_reg = compile_expression(left_str, ctx);
                    size_t right_reg = compile_expression(right_str, ctx);
                    
                    if (left_reg == static_cast<size_t>(-1) || right_reg == static_cast<size_t>(-1)) {
                        return static_cast<size_t>(-1);
                    }
                    
                    size_t result_reg = allocate_register(ctx);
                    ctx.function->bytecode.push_back(Instruction::binary_op(cmp.opcode, result_reg, left_reg, right_reg));
                    return result_reg;
                }
            }
        }
    }
    
    // 处理乘法和除法表达式（优先级最高）
    size_t last_mul_pos = std::string::npos;
    size_t last_div_pos = std::string::npos;
    int paren_count = 0;
    
    // 查找最后一个乘号或除号（不在括号内）
    paren_count = 0;
    for (int i = static_cast<int>(trimmed.length()) - 1; i >= 0; i--) {
        if (trimmed[i] == ')') {
            paren_count++;
        } else if (trimmed[i] == '(') {
            paren_count--;
        } else if (paren_count == 0) {
            if (trimmed[i] == '*' && i > 0) {
                last_mul_pos = i;
                break;
            } else if (trimmed[i] == '/' && i > 0) {
                last_div_pos = i;
                break;
            }
        }
    }
    
    if (last_mul_pos != std::string::npos) {
        std::string left_str = trimmed.substr(0, last_mul_pos);
        std::string right_str = trimmed.substr(last_mul_pos + 1);
        
        size_t left_reg = compile_expression(left_str, ctx);
        size_t right_reg = compile_expression(right_str, ctx);
        
        if (left_reg == static_cast<size_t>(-1) || right_reg == static_cast<size_t>(-1)) {
            return static_cast<size_t>(-1);
        }
        
        size_t result_reg = allocate_register(ctx);
        ctx.function->bytecode.push_back(Instruction::binary_op(OpCode::MUL, result_reg, left_reg, right_reg));
        return result_reg;
    }
    
    if (last_div_pos != std::string::npos) {
        std::string left_str = trimmed.substr(0, last_div_pos);
        std::string right_str = trimmed.substr(last_div_pos + 1);
        
        size_t left_reg = compile_expression(left_str, ctx);
        size_t right_reg = compile_expression(right_str, ctx);
        
        if (left_reg == static_cast<size_t>(-1) || right_reg == static_cast<size_t>(-1)) {
            return static_cast<size_t>(-1);
        }
        
        size_t result_reg = allocate_register(ctx);
        ctx.function->bytecode.push_back(Instruction::binary_op(OpCode::DIV, result_reg, left_reg, right_reg));
        return result_reg;
    }
    
    // 处理加法和减法表达式（优先级中等）
    // 查找加法和减法运算符（从右到左，确保正确的结合性）
    size_t last_plus_pos = std::string::npos;
    size_t last_minus_pos = std::string::npos;
    paren_count = 0;
    for (int i = static_cast<int>(trimmed.length()) - 1; i >= 0; i--) {
        if (trimmed[i] == ')') {
            paren_count++;
        } else if (trimmed[i] == '(') {
            paren_count--;
        } else if (paren_count == 0) {
            if (trimmed[i] == '+' && i > 0) {
                last_plus_pos = i;
                break;
            } else if (trimmed[i] == '-' && i > 0) {
                last_minus_pos = i;
                break;
            }
        }
    }
    
    // 优先处理减法（因为加法和减法优先级相同，从左到右结合）
    if (last_minus_pos != std::string::npos) {
        std::string left_str = trimmed.substr(0, last_minus_pos);
        std::string right_str = trimmed.substr(last_minus_pos + 1);
        
        size_t left_reg = compile_expression(left_str, ctx);
        size_t right_reg = compile_expression(right_str, ctx);
        
        if (left_reg == static_cast<size_t>(-1) || right_reg == static_cast<size_t>(-1)) {
            return static_cast<size_t>(-1);
        }
        
        size_t result_reg = allocate_register(ctx);
        ctx.function->bytecode.push_back(Instruction::binary_op(OpCode::SUB, result_reg, left_reg, right_reg));
        return result_reg;
    }
    
    if (last_plus_pos != std::string::npos) {
        std::string left_str = trimmed.substr(0, last_plus_pos);
        std::string right_str = trimmed.substr(last_plus_pos + 1);
        
        size_t left_reg = compile_expression(left_str, ctx);
        size_t right_reg = compile_expression(right_str, ctx);
        
        if (left_reg == static_cast<size_t>(-1) || right_reg == static_cast<size_t>(-1)) {
            return static_cast<size_t>(-1);
        }
        
        size_t result_reg = allocate_register(ctx);
        ctx.function->bytecode.push_back(Instruction::binary_op(OpCode::ADD, result_reg, left_reg, right_reg));
        return result_reg;
    }
    
    // 处理字符串字面量
    if (!trimmed.empty() && (trimmed[0] == '\'' || trimmed[0] == '"')) {
        char quote = trimmed[0];
        size_t end_quote = trimmed.find(quote, 1);
        if (end_quote != std::string::npos) {
            std::string str_value = trimmed.substr(1, end_quote - 1);
            size_t const_idx = add_constant(ctx, Value(str_value));
            size_t reg = allocate_register(ctx);
            ctx.function->bytecode.push_back(Instruction::load_const(reg, const_idx));
            return reg;
        }
    }
    
    // 处理list字面量 [1, 2, 3]
    if (!trimmed.empty() && trimmed[0] == '[') {
        return compile_list_literal(trimmed, ctx);
    }
    
    // 处理dict字面量 {"a": 1, "b": 2}
    if (!trimmed.empty() && trimmed[0] == '{') {
        return compile_dict_literal(trimmed, ctx);
    }
    
    // 处理数字字面量
    try {
        double value = std::stod(trimmed);
        size_t const_idx = add_constant(ctx, Value(value));
        size_t reg = allocate_register(ctx);
        ctx.function->bytecode.push_back(Instruction::load_const(reg, const_idx));
        return reg;
    } catch (...) {
        // 处理变量名 - 修复变量名识别
        auto it = ctx.variable_registers.find(trimmed);
        if (it != ctx.variable_registers.end()) {
            return it->second;
        } else {
            // 允许未定义的变量名作为表达式（运行时错误）
            // 分配一个新的寄存器，但标记为未定义
            size_t reg = allocate_register(ctx, trimmed);
            return reg;
        }
    }
}

bool Compiler::compile_expression_and_store(const std::string& expr, const std::string& var_name, 
                                           CompileContext& ctx, size_t line_num) {
    size_t value_reg = compile_expression(expr, ctx);
    if (value_reg == static_cast<size_t>(-1)) {
        return false;
    }
    
    size_t var_reg = allocate_register(ctx, var_name);
    
    // 使用MOVE指令存储到局部变量
    ctx.function->bytecode.push_back(Instruction(OpCode::MOVE, var_reg, value_reg, 0));
    
    // 更新调试信息
    size_t bytecode_offset = ctx.function->bytecode.size() - 1;
    ctx.debug_info->add_line_mapping(bytecode_offset, line_num);
    
    return true;
}

bool Compiler::compile_let_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    size_t eq_pos = stmt.find('=');
    if (eq_pos == std::string::npos) return false;
    
    std::string var_name = stmt.substr(4, eq_pos - 4);
    var_name.erase(0, var_name.find_first_not_of(" \t"));
    var_name.erase(var_name.find_last_not_of(" \t") + 1);
    
    std::string expr = stmt.substr(eq_pos + 1);
    expr.erase(0, expr.find_first_not_of(" \t"));
    expr.erase(expr.find_last_not_of(" \t\r\n") + 1);
    
    return compile_expression_and_store(expr, var_name, ctx, line_num);
}

bool Compiler::compile_echo_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    std::string expr = stmt.substr(5);
    expr.erase(0, expr.find_first_not_of(" \t"));
    expr.erase(expr.find_last_not_of(" \t\r\n") + 1);
    
    size_t reg = compile_expression(expr, ctx);
    if (reg == static_cast<size_t>(-1)) return false;
    
    // 生成ECHO指令输出表达式结果
    ctx.function->bytecode.push_back(Instruction(OpCode::ECHO, reg, 0, 0, 0));
    
    // 更新调试信息
    size_t bytecode_offset = ctx.function->bytecode.size() - 1;
    ctx.debug_info->add_line_mapping(bytecode_offset, line_num);
    
    return true;
}

bool Compiler::compile_expression_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    // 表达式语句 - 计算但不存储结果
    size_t reg = compile_expression(stmt, ctx);
    if (reg == static_cast<size_t>(-1)) return false;
    
    return true;
}

size_t Compiler::add_constant(CompileContext& ctx, const Value& value) {
    auto it = ctx.constants.find(value.to_string());
    if (it != ctx.constants.end()) {
        return it->second;
    }
    
    size_t index = ctx.constant_pool.size();
    ctx.constant_pool.push_back(value);
    ctx.constants[value.to_string()] = index;
    
    return index;
}

size_t Compiler::allocate_register(CompileContext& ctx, const std::string& var_name) {
    if (!var_name.empty()) {
        // 如果变量已存在，返回现有的寄存器
        auto it = ctx.variable_registers.find(var_name);
        if (it != ctx.variable_registers.end()) {
            return it->second;
        }
        // 否则分配新的寄存器
        size_t reg = ctx.next_register++;
        ctx.variable_registers[var_name] = reg;
        ctx.debug_info->var_map[var_name] = reg;
        return reg;
    }
    // 匿名变量分配新寄存器
    return ctx.next_register++;
}

void Compiler::update_line_mapping(CompileContext& ctx, size_t bytecode_offset, size_t source_line) {
    ctx.debug_info->add_line_mapping(static_cast<uint32_t>(bytecode_offset), static_cast<uint32_t>(source_line));
}

size_t Compiler::compile_list_literal(const std::string& expr, CompileContext& ctx) {
    if (expr.empty() || expr[0] != '[' || expr.back() != ']') {
        return static_cast<size_t>(-1);
    }
    
    std::string content = expr.substr(1, expr.length() - 2);
    content.erase(0, content.find_first_not_of(" \t"));
    content.erase(content.find_last_not_of(" \t\r\n") + 1);
    
    // 创建新列表
    size_t list_reg = allocate_register(ctx);
    ctx.function->bytecode.push_back(Instruction(OpCode::NEW_LIST, list_reg, 0, 0, 0));
    
    if (!content.empty()) {
        // 解析元素
        std::vector<std::string> elements;
        std::string current;
        int bracket_depth = 0;
        int brace_depth = 0;
        bool in_string = false;
        char string_quote = 0;
        
        for (char c : content) {
            if (!in_string && (c == '\'' || c == '"')) {
                in_string = true;
                string_quote = c;
                current += c;
            } else if (in_string && c == string_quote) {
                in_string = false;
                string_quote = 0;
                current += c;
            } else if (!in_string) {
                if (c == '[') bracket_depth++;
                else if (c == ']') bracket_depth--;
                else if (c == '{') brace_depth++;
                else if (c == '}') brace_depth--;
                else if (c == ',' && bracket_depth == 0 && brace_depth == 0) {
                    elements.push_back(current);
                    current.clear();
                    continue;
                }
                current += c;
            } else {
                current += c;
            }
        }
        
        if (!current.empty()) {
            elements.push_back(current);
        }
        
        // 编译每个元素并添加到list中
        for (const auto& elem_str : elements) {
            std::string trimmed_elem = elem_str;
            trimmed_elem.erase(0, trimmed_elem.find_first_not_of(" \t"));
            trimmed_elem.erase(trimmed_elem.find_last_not_of(" \t") + 1);
            
            if (!trimmed_elem.empty()) {
                size_t elem_reg = compile_expression(trimmed_elem, ctx);
                if (elem_reg == static_cast<size_t>(-1)) {
                    return static_cast<size_t>(-1);
                }
                
                // 使用LIST_APPEND指令添加元素到列表
                ctx.function->bytecode.push_back(Instruction::list_append(list_reg, elem_reg));
            }
        }
    }
    
    return list_reg;
}

size_t Compiler::compile_dict_literal(const std::string& expr, CompileContext& ctx) {
    if (expr.empty() || expr[0] != '{' || expr.back() != '}') {
        return static_cast<size_t>(-1);
    }
    
    std::string content = expr.substr(1, expr.length() - 2);
    content.erase(0, content.find_first_not_of(" \t"));
    content.erase(content.find_last_not_of(" \t\r\n") + 1);
    
    // 创建新字典
    size_t dict_reg = allocate_register(ctx);
    ctx.function->bytecode.push_back(Instruction(OpCode::NEW_DICT, dict_reg, 0, 0, 0));
    
    if (!content.empty()) {
        // 解析键值对
        std::vector<std::string> pairs;
        std::string current;
        int bracket_depth = 0;
        int brace_depth = 0;
        bool in_string = false;
        char string_quote = 0;
        
        for (char c : content) {
            if (!in_string && (c == '\'' || c == '"')) {
                in_string = true;
                string_quote = c;
                current += c;
            } else if (in_string && c == string_quote) {
                in_string = false;
                string_quote = 0;
                current += c;
            } else if (!in_string) {
                if (c == '[') bracket_depth++;
                else if (c == ']') bracket_depth--;
                else if (c == '{') brace_depth++;
                else if (c == '}') brace_depth--;
                else if (c == ',' && bracket_depth == 0 && brace_depth == 0) {
                    pairs.push_back(current);
                    current.clear();
                    continue;
                }
                current += c;
            } else {
                current += c;
            }
        }
        
        if (!current.empty()) {
            pairs.push_back(current);
        }
        
        // 编译每个键值对
        for (const auto& pair_str : pairs) {
            std::string trimmed_pair = pair_str;
            trimmed_pair.erase(0, trimmed_pair.find_first_not_of(" \t"));
            trimmed_pair.erase(trimmed_pair.find_last_not_of(" \t") + 1);
            
            size_t colon_pos = trimmed_pair.find(':');
            if (colon_pos != std::string::npos) {
                std::string key_str = trimmed_pair.substr(0, colon_pos);
                std::string value_str = trimmed_pair.substr(colon_pos + 1);
                
                key_str.erase(0, key_str.find_first_not_of(" \t"));
                key_str.erase(key_str.find_last_not_of(" \t") + 1);
                
                value_str.erase(0, value_str.find_first_not_of(" \t"));
                value_str.erase(value_str.find_last_not_of(" \t") + 1);
                
                // 处理字符串键
                std::string key;
                if (!key_str.empty() && (key_str[0] == '\'' || key_str[0] == '"')) {
                    char quote = key_str[0];
                    if (key_str.length() >= 2 && key_str.back() == quote) {
                        key = key_str.substr(1, key_str.length() - 2);
                    } else {
                        key = key_str;
                    }
                } else {
                    key = key_str;
                }
                
                if (!value_str.empty()) {
                    size_t value_reg = compile_expression(value_str, ctx);
                    if (value_reg == static_cast<size_t>(-1)) {
                        return static_cast<size_t>(-1);
                    }
                    
                    // 编译键表达式
                    size_t key_reg = compile_expression(key_str, ctx);
                    if (key_reg == static_cast<size_t>(-1)) {
                        return static_cast<size_t>(-1);
                    }
                    
                    // 使用DICT_SET指令设置键值对
                    ctx.function->bytecode.push_back(Instruction::dict_set(dict_reg, key_reg, value_reg));
                }
            }
        }
    }
    
    return dict_reg;
}

bool Compiler::compile_if_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    std::string condition;
    
    // 提取条件表达式
    size_t if_pos = stmt.find("if");
    if (if_pos == std::string::npos) {
        return false;
    }
    
    // 找到if后面的部分
    std::string after_if = stmt.substr(if_pos + 2);
    after_if.erase(0, after_if.find_first_not_of(" \t"));
    
    // 提取括号内的内容
    if (!after_if.empty() && after_if[0] == '(') {
        size_t close_pos = after_if.find(')');
        if (close_pos != std::string::npos) {
            condition = after_if.substr(1, close_pos - 1);
        } else {
            condition = after_if.substr(1);
        }
    } else {
        condition = after_if;
    }
    
    condition.erase(0, condition.find_first_not_of(" \t"));
    condition.erase(condition.find_last_not_of(" \t\r\n") + 1);
    
    if (condition.empty()) {
        return false;
    }
    
    // 编译条件表达式
    size_t cond_reg = compile_expression(condition, ctx);
    if (cond_reg == static_cast<size_t>(-1)) {
        return false;
    }
    
    // 创建跳转指令 - 使用绝对地址
    size_t jump_offset = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction(OpCode::JMP_IF_FALSE, cond_reg, 0, 0, 0));
    update_line_mapping(ctx, jump_offset, line_num);
    
    // 记录需要回填的跳转位置
    ctx.if_stack.push_back(IfInfo{jump_offset, false});
    
    return true;
}

bool Compiler::compile_elseif_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    if (ctx.if_stack.empty()) {
        return false; // 没有对应的if语句
    }
    
    // 回填上一个条件的跳转
    auto& if_info = ctx.if_stack.back();
    if (if_info.has_else) {
        return false; // 已经有else语句
    }
    
    // 创建跳转到endif的指令，记录位置用于回填
    size_t jmp_pos = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction::jump(OpCode::JMP, 0));
    
    // 回填上一个条件的跳转
    ctx.function->bytecode[if_info.jump_pos].bx = ctx.function->bytecode.size();
    
    size_t cond_reg;
    size_t jump_offset;
    
    // 提取新的条件表达式
    std::string condition = stmt.substr(6);
    condition.erase(0, condition.find_first_not_of(" \t"));
    condition.erase(condition.find_last_not_of(" \t\r\n") + 1);
    
    cond_reg = compile_expression(condition, ctx);
    if (cond_reg == static_cast<size_t>(-1)) {
        return false;
    }
    
    // 创建新的条件跳转
    jump_offset = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction(OpCode::JMP_IF_FALSE, cond_reg, 0, 0, 0));
    update_line_mapping(ctx, jump_offset, line_num);
    
    if_info.jump_pos = jump_offset;
    
    return true;
}

bool Compiler::compile_else_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    if (ctx.if_stack.empty()) {
        return false; // 没有对应的if语句
    }
    
    auto& if_info = ctx.if_stack.back();
    if (if_info.has_else) {
        return false; // 已经有else语句
    }
    
    // 创建跳转到endif的指令
    size_t jmp_pos = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction::jump(OpCode::JMP, 0));
    
    // 回填上一个条件的跳转
    ctx.function->bytecode[if_info.jump_pos].bx = ctx.function->bytecode.size();
    
    // 更新跳转位置为当前JMP指令
    if_info.has_else = true;
    if_info.jump_pos = jmp_pos;
    
    return true;
}

bool Compiler::compile_endif_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    if (ctx.if_stack.empty()) {
        return false; // 没有对应的if语句
    }
    
    auto& if_info = ctx.if_stack.back();
    
    // 回填最后一个跳转到当前位置
    ctx.function->bytecode[if_info.jump_pos].bx = ctx.function->bytecode.size();
    
    ctx.if_stack.pop_back();
    return true;
}

bool Compiler::compile_while_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    // 提取条件表达式
    std::string condition = stmt;
    if (condition.find("while ") == 0) {
        condition = condition.substr(6);
    } else if (condition.find("while(") == 0) {
        condition = condition.substr(6);
    }
    
    condition.erase(0, condition.find_first_not_of(" \t"));
    condition.erase(condition.find_last_not_of(" \t\r\n") + 1);
    
    // 记录循环开始位置 - 这是条件表达式的位置
    size_t loop_start = ctx.function->bytecode.size();
    
    // 编译条件表达式 - 每次循环都会重新执行到这里
    size_t cond_reg = compile_expression(condition, ctx);
    if (cond_reg == static_cast<size_t>(-1)) {
        return false;
    }
    
    // 创建条件跳转 - 如果条件为假则跳出循环
    size_t jump_offset = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction(OpCode::JMP_IF_FALSE, cond_reg, 0, 0, 0));
    update_line_mapping(ctx, jump_offset, line_num);
    
    // 记录循环信息
    ctx.while_stack.push_back(WhileInfo{loop_start, jump_offset, condition, cond_reg});
    
    return true;
}

bool Compiler::compile_endwhile_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    if (ctx.while_stack.empty()) {
        std::cerr << "Error: endwhile without while at line " << line_num << std::endl;
        return false;
    }
    
    WhileInfo info = ctx.while_stack.back();
    ctx.while_stack.pop_back();
    
    // 创建跳回循环开始的指令 - 跳回到条件表达式重新计算的位置
    size_t jmp_back = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction(OpCode::JMP, 0, 0, 0, 0));
    ctx.function->bytecode.back().bx = info.loop_start;
    update_line_mapping(ctx, jmp_back, line_num);
    
    // 回填条件跳转目标地址 - 跳转到循环结束后的位置（即endwhile之后）
    ctx.function->bytecode[info.jump_pos].bx = jmp_back + 1;
    
    return true;
}

bool Compiler::compile_for_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    // 解析for循环语法：for var in list_expr
    std::string after_for = stmt.substr(3); // 跳过"for"
    after_for.erase(0, after_for.find_first_not_of(" \t"));
    
    // 查找"in"关键字
    size_t in_pos = after_for.find(" in ");
    if (in_pos == std::string::npos) {
        in_pos = after_for.find(" ");
        if (in_pos == std::string::npos || after_for.substr(in_pos + 1).find("in") != 0) {
            return false;
        }
        in_pos = in_pos + 1;
    }
    
    // 提取变量名
    std::string var_name = after_for.substr(0, in_pos);
    var_name.erase(0, var_name.find_first_not_of(" \t"));
    var_name.erase(var_name.find_last_not_of(" \t") + 1);
    
    // 提取列表表达式
    std::string list_expr = after_for.substr(in_pos + 3);
    list_expr.erase(0, list_expr.find_first_not_of(" \t"));
    list_expr.erase(list_expr.find_last_not_of(" \t\r\n") + 1);
    
    if (var_name.empty() || list_expr.empty()) {
        return false;
    }
    
    // 编译列表表达式
    size_t list_reg = compile_expression(list_expr, ctx);
    if (list_reg == static_cast<size_t>(-1)) {
        return false;
    }
    
    // 分配循环变量寄存器
    size_t var_reg = allocate_register(ctx, var_name);
    
    // 分配索引寄存器
    size_t index_reg = allocate_register(ctx);
    size_t const_zero = add_constant(ctx, Value(0.0));
    ctx.function->bytecode.push_back(Instruction::load_const(index_reg, const_zero));
    
    // 分配长度寄存器
    size_t len_reg = allocate_register(ctx);
    ctx.function->bytecode.push_back(Instruction(OpCode::LEN, len_reg, list_reg, 0, 0));
    
    // 记录循环开始位置
    size_t loop_start = ctx.function->bytecode.size();
    
    // 检查索引是否小于长度
    size_t cmp_reg = allocate_register(ctx);
    ctx.function->bytecode.push_back(Instruction::binary_op(OpCode::LT, cmp_reg, index_reg, len_reg));
    
    // 条件跳转 - 如果索引 >= 长度则跳出循环
    size_t jump_offset = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction(OpCode::JMP_IF_FALSE, cmp_reg, 0, 0, 0));
    update_line_mapping(ctx, jump_offset, line_num);
    
    // 获取当前元素
    size_t item_reg = allocate_register(ctx);
    ctx.function->bytecode.push_back(Instruction(OpCode::GET_INDEX, item_reg, list_reg, index_reg));
    
    // 将当前元素赋值给循环变量
    ctx.function->bytecode.push_back(Instruction(OpCode::MOVE, var_reg, item_reg, 0));
    
    // 记录循环信息
    ctx.for_stack.push_back(ForInfo{loop_start, jump_offset, var_name, list_reg, index_reg, len_reg, item_reg});
    
    return true;
}

bool Compiler::compile_endfor_statement(const std::string& stmt, CompileContext& ctx, size_t line_num) {
    if (ctx.for_stack.empty()) {
        std::cerr << "Error: endfor without for at line " << line_num << std::endl;
        return false;
    }
    
    ForInfo info = ctx.for_stack.back();
    ctx.for_stack.pop_back();
    
    // 索引加1
    size_t const_one = add_constant(ctx, Value(1.0));
    size_t temp_reg = allocate_register(ctx);
    ctx.function->bytecode.push_back(Instruction::load_const(temp_reg, const_one));
    ctx.function->bytecode.push_back(Instruction::binary_op(OpCode::ADD, info.index_reg, info.index_reg, temp_reg));
    
    // 跳回循环开始位置
    size_t jmp_back = ctx.function->bytecode.size();
    ctx.function->bytecode.push_back(Instruction(OpCode::JMP, 0, 0, 0, 0));
    ctx.function->bytecode.back().bx = info.loop_start;
    update_line_mapping(ctx, jmp_back, line_num);
    
    // 回填条件跳转目标地址
    ctx.function->bytecode[info.jump_pos].bx = jmp_back + 1;
    
    return true;
}
} // namespace viml